package com.tgu.home_action.controller.filter;

import com.tgu.home_action.pojo.ResponseData;
import com.tgu.home_action.pojo.exception.RedisTokenErrorException;
import com.tgu.home_action.pojo.exception.RedisTokenNullException;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.utils.JwtService;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private Logger logger;
    @Autowired
    private JwtService jwtService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf8");
        response.setContentType("text/json;charset = UTF-8");
        ResponseData<Object> responseData = new ResponseData<>();
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            responseData.setMessageState(ResponseState.TOKEN_NOT_PROVIDE.getMessage(), ResponseState.TOKEN_NOT_PROVIDE.getValue());
            String result = JSON.toJSONString(responseData);
            response.getWriter().append(result);
            return false;
        }
        String[] bearer = authorization.split(" ");
        if (!bearer[0].equals("Bearer")) {
            responseData.setMessageState(ResponseState.TOKEN_IS_ERROR.getMessage(), ResponseState.TOKEN_IS_ERROR.getValue());
            String result = JSON.toJSONString(responseData);
            response.getWriter().append(result);
            return false;
        }
        String token = bearer[1];
        try {
            UserDetails userDetails = jwtService.getUserDetails(token, request);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                    request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return true;
        } catch (RedisTokenErrorException e) {
            logger.warn("token错误");
            logger.error(e.getMessage());
            responseData.setMessageState(ResponseState.TOKEN_IS_ERROR.getMessage(), ResponseState.TOKEN_IS_ERROR.getValue());//101
            String Json = JSON.toJSONString(responseData);
            response.getWriter().append(Json);
            return false;
        } catch (RedisTokenNullException | ExpiredJwtException e) {
            logger.warn("token已过期");
            logger.error(e.getMessage());
            responseData.setMessageState("token已过期", ResponseState.TOKEN_IS_EXPIRED.getValue());
            String Json = JSON.toJSONString(responseData);
            response.getWriter().append(Json);
            return false;
        } catch (Exception e) {
            System.out.println(e);
            logger.error("发生错误");
            logger.error(e.getMessage());
            responseData.setMessageState(ResponseState.TOKEN_IS_ERROR.getMessage(), ResponseState.TOKEN_IS_ERROR.getValue());
            String Json = JSON.toJSONString(responseData);
            response.getWriter().append(Json);
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
